/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.franmontiel.persistentcookiejar.persistence;

import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import okhttp3.Cookie;

/**
 * This class is used to prepare preferences which will used to store data.
 * It extends {@link CookiePersistor} which has all methods like save, remove, clear etc
 */
public class SharedPrefsCookiePersistor implements CookiePersistor {
    private final Preferences sharedPreferences;
    private DatabaseHelper mDatabaseHelper;

    public SharedPrefsCookiePersistor(Context context) {
        this(new DatabaseHelper(context));
    }

    public SharedPrefsCookiePersistor(DatabaseHelper databaseHelper) {
        this(databaseHelper.getPreferences("CookiePersistence"));
        mDatabaseHelper = databaseHelper;
    }

    public SharedPrefsCookiePersistor(Preferences sharedPreferences) {
        this.sharedPreferences = sharedPreferences;
    }

    @Override
    public List<Cookie> loadAll() {
        List<Cookie> cookies = new ArrayList<>(sharedPreferences.getAll().size());
        for (Map.Entry<String, ?> entry : sharedPreferences.getAll().entrySet()) {
            if (entry.getValue() instanceof String) {
                String serializedCookie = (String) entry.getValue();
                Cookie cookie = new SerializableCookie().decode(serializedCookie);
                if (cookie != null) {
                    cookies.add(cookie);
                }
            }
        }
        return cookies;
    }

    @Override
    public void saveAll(Collection<Cookie> cookies) {
        for (Cookie cookie : cookies) {
            sharedPreferences.putString(createCookieKey(cookie), new SerializableCookie().encode(cookie));
        }
        sharedPreferences.flushSync();
    }

    @Override
    public void removeAll(Collection<Cookie> cookies) {
        for (Cookie cookie : cookies) {
            sharedPreferences.delete(createCookieKey(cookie));
        }
        mDatabaseHelper.removePreferencesFromCache("CookiePersistence");
    }

    /**
     * This method is used to create key for the Cookie
     *
     * @param cookie Cookie object to get all information to create a key
     * @return String value for the prepared key
     */
    private static String createCookieKey(Cookie cookie) {
        return (cookie.secure() ? "https" : "http") + "://" + cookie.domain() + cookie.path() + "|" + cookie.name();
    }

    @Override
    public void clear() {
        sharedPreferences.clear().flushSync();
    }
}